package com.wthink.hzgj.busInfo

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.navigation.findNavController
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.R
import com.wthink.hzgj.busInfo.viewmodel.BusConfigViewmodel
import com.wthink.hzgj.databinding.FragmentBusconfigBinding
import com.wthink.hzgj.util.toast

class BusConfigFragment : Fragment(){

    val busColor = MutableLiveData("")

    private val viewModel by viewModels<BusConfigViewmodel>()

    private lateinit var binding: FragmentBusconfigBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_busconfig,
            container,
            false
        )
        binding.viewModel = viewModel
        binding.lifecycleOwner = this

        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        binding.back.setOnClickListener {
            it.findNavController().popBackStack()
        }

        binding.spinnerColor.onItemSelectedListener =  object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                busColor.postValue(viewModel.colorsItems[position])
            }
        }

        binding.settings.setOnClickListener {
                val vdrModel = viewModel.vdr_model.value
                val vdr_vendorid = viewModel.vdr_vendorid.value
                val vid = viewModel.vid.value
                val simno = viewModel.simno.value
                val car_num = viewModel.car_num.value
                val province_id = viewModel.province_id.value
                val city_id = viewModel.city_id.value
                val car_vin = viewModel.car_vin.value

             if (vdrModel!!.isEmpty() || vdr_vendorid!!.isEmpty() || vid!!.isEmpty()
                 ||simno!!.isEmpty() || car_num!!.isEmpty() || province_id!!.isEmpty()
                 || city_id!!.isEmpty() || car_vin!!.isEmpty()
             ) {
                 toast(BusApplication.busContext,"请输入完整配置信息")
                 return@setOnClickListener
             }

             viewModel.config(
                 BusInfo(
                     vdrModel,vdr_vendorid,vid
                 ,simno,car_num, busColor.value!!,city_id,province_id,car_vin))
         }
    }
}